package com.mojiayi.learn.almp;

import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.mojiayi.learn.almp.request.EditAppInfoParam;
import com.mojiayi.learn.almp.request.LoginParam;
import com.mojiayi.learn.almp.response.AppInfoData;
import com.mojiayi.learn.almp.response.AppInfoResponse;
import com.mojiayi.learn.almp.response.AppListResponse;
import com.mojiayi.learn.almp.response.LoginResponse;
import com.mojiayi.learn.almp.response.ResponseCommon;
import com.mojiayi.learn.almp.response.TeamMember;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class EditAlmpPersonTest {
    private static final String SUCCESS_CODE = "10001000005";
    private static String token = null;
    private static final List<TeamMember> allDeveloperPersonList = new ArrayList<>();
    private static final List<TeamMember> testPersons = new ArrayList<>();
    private static final Map<String, AlmpAppPersonList> appPersonMap = new HashMap<>();
    private static final List<String> defaultObligationPersonNames = new ArrayList<>();
    private static String LOGIN_NAME = null;
    private static String LOGIN_PASSWORD = null;

    static {
        // 设置操作人账号和密码
        LOGIN_NAME = "";
        LOGIN_PASSWORD = "";

        // 每个应用的默认负责人
        defaultObligationPersonNames.add("liguangri");
        defaultObligationPersonNames.add("zhaoliang");

        // 初始化测试人员
        initTestPerson("zhaowenxiu43642");
        initTestPerson("wenya");
        initTestPerson("luohao");

        // 初始化团队中的后端开发人员
        initDevelopPerson("liuxingdong");
        initDevelopPerson("zhangxiangtao");
        initDevelopPerson("zhaoliang");
        initDevelopPerson("wangchenguo");
        initDevelopPerson("longyongqing");
        initDevelopPerson("liguangri");
        initDevelopPerson("tangyao37869");
        initDevelopPerson("lizejin");

        // 为每个应用分配开发人员、测试人员和负责人
        // 每个应用的测试人员都相同，负责人专门指定，有一两个管理所有应用的负责人，开发人员是除负责人之外的其他所有开发
        initAppPersionList("taoli-biz-web", "longyongqing");
        initAppPersionList("taoli-client-web", null);
        initAppPersionList("taoli-user-profile", "wangchenguo");
        initAppPersionList("taoli-plugin-deploy", "wangchenguo");
        initAppPersionList("taoli-ai-call-dubbo", "zhangxiangtao");
        initAppPersionList("taoli-ai-call-quartz", "zhangxiangtao");
        initAppPersionList("taoli-manual-call-service", "zhangxiangtao");
        initAppPersionList("taoli-data-deploy", null);
        initAppPersionList("accrual-api", "liuxingdong");
        initAppPersionList("accrual-data", "liuxingdong");
        initAppPersionList("accrual-task", "liuxingdong");
        initAppPersionList("edu-power-dubbo", "liuxingdong");
        initAppPersionList("taoli-enrol-deploy", "zhangxiangtao");
        initAppPersionList("taoli-contract-dubbo", null);
        initAppPersionList("taoli-enrol-dubbo", "liuxingdong");
        initAppPersionList("taoli-enrol-quartz", "longyongqing");
        initAppPersionList("taoli-sdk-dubbo", "wangchenguo");
        initAppPersionList("taoli-enrol-mq", "longyongqing");
        initAppPersionList("taoli-statis-dubbo", null);
        initAppPersionList("taoli-visit-dubbo", "zhangxiangtao");
        initAppPersionList("taoli-learn-process-management-deploy", "longyongqing");
        initAppPersionList("taoli-visit-quartz", "zhangxiangtao");
        initAppPersionList("taoli-class-management-deploy", null);
        initAppPersionList("taoli-course-permission", "liuxingdong");
        initAppPersionList("taoli-homework-deploy", null);
        initAppPersionList("investigate-provider-server", null);
        initAppPersionList("taoli-chat", "longyongqing");
        initAppPersionList("taoli-mq", null);
    }

    private static void initTestPerson(String name) {
        TeamMember teamMember = new TeamMember();
        teamMember.setName(name);
        teamMember.setPosition("测试人员");
        testPersons.add(teamMember);
    }

    private static void initDevelopPerson(String name) {
        TeamMember teamMember = new TeamMember();
        teamMember.setName(name);
        teamMember.setPosition("开发人员");
        allDeveloperPersonList.add(teamMember);
    }

    /**
     * 设置每个app的开发人员、测试人员和负责人
     *
     * @param appName              app名称
     * @param obligationPersonName 指定的专职负责人，不管是否指定专职负责人，每个应用另外还会有一两个管理所有应用的负责人
     */
    private static void initAppPersionList(String appName, String obligationPersonName) {
        List<String> obligationPersonNames = new ArrayList<>();
        if (StringUtils.isNotEmpty(obligationPersonName)) {
            obligationPersonNames.add(obligationPersonName);
        }
        obligationPersonNames.addAll(defaultObligationPersonNames);

        AlmpAppPersonList appPersonList = new AlmpAppPersonList();
        appPersonList.setAppName(appName);
        appPersonList.setTestPersons(testPersons.stream().distinct().collect(Collectors.toList()));
        appPersonList.setObligationPerson(allDeveloperPersonList.stream().filter(v -> obligationPersonNames.contains(v.getName())).distinct().collect(Collectors.toList()));
        appPersonList.setDevelopPersons(allDeveloperPersonList.stream().filter(v -> !obligationPersonNames.contains(v.getName())).distinct().collect(Collectors.toList()));

        appPersonMap.put(appName, appPersonList);
    }

    public static void main(String[] args) {
        token = login(LOGIN_NAME, LOGIN_PASSWORD);
        if (StringUtils.isEmpty(token)) {
            return;
        }

        AppListResponse appList = getAppInfoList();
        if (appList == null || CollectionUtils.isEmpty(appList.getData().getRecords())) {
            return;
        }
        for (AppInfoData appInfo : appList.getData().getRecords()) {
            if (!appPersonMap.containsKey(appInfo.getAppName())) {
                continue;
            }
            AppInfoResponse appInfoResponse = getAppAuditInfo(appInfo.getAppId());
            if (appInfoResponse == null) {
                continue;
            }
            editAppInfoAudit(appInfoResponse);
        }
    }

    private static String login(String loginName, String loginPassword) {
        String url = "https://almp.shiguangkey.com/api/user/login";
        LoginParam loginParam = new LoginParam(loginName, loginPassword);
        HttpRequest postRequest = HttpUtil.createPost(url);
        Gson gson = new Gson();
        postRequest.body(gson.toJson(loginParam));
        HttpResponse postResponse = postRequest.execute();
        Assert.isTrue(HttpStatus.HTTP_OK == postResponse.getStatus());

        LoginResponse loginResponse = gson.fromJson(postResponse.body(), LoginResponse.class);
        Assert.isTrue(SUCCESS_CODE.equals(loginResponse.getCode()));
        return loginResponse.getData();
    }

    private static AppListResponse getAppInfoList() {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        String url = "https://almp.shiguangkey.com/api/app-info/list?buildState=1";
        HttpRequest getRequest = HttpUtil.createGet(url);
        getRequest.header("token", token);
        HttpResponse getResponse = getRequest.execute();
        Assert.isTrue(HttpStatus.HTTP_OK == getResponse.getStatus());

        Gson gson = new Gson();
        AppListResponse appListResponse = gson.fromJson(getResponse.body(), AppListResponse.class);
        Assert.isTrue(SUCCESS_CODE.equals(appListResponse.getCode()));

        String reToken = getResponse.header("reToken");
        if (StringUtils.isNotEmpty(reToken) && !reToken.equals(token)) {
            token = reToken;
        }
        return appListResponse;
    }

    private static AppInfoResponse getAppAuditInfo(long appId) {
        if (appId <= 0) {
            return null;
        }
        String url = "https://almp.shiguangkey.com/api/app-info/audit/id?appId=" + appId;
        HttpRequest getRequest = HttpUtil.createGet(url);
        getRequest.header("token", token);
        HttpResponse getResponse = getRequest.execute();
        Assert.isTrue(HttpStatus.HTTP_OK == getResponse.getStatus());

        String responseBody = getResponse.body();
        Gson gson = new Gson();
        AppInfoResponse appInfoResponse = gson.fromJson(responseBody, AppInfoResponse.class);
        Assert.isTrue(SUCCESS_CODE.equals(appInfoResponse.getCode()));

        String reToken = getResponse.header("reToken");
        if (StringUtils.isNotEmpty(reToken) && !reToken.equals(token)) {
            token = reToken;
        }
        return appInfoResponse;
    }

    private static void editAppInfoAudit(AppInfoResponse appInfoResponse) {
        AppInfoData appInfoData = appInfoResponse.getData();
        EditAppInfoParam editAppInfoParam = new EditAppInfoParam();
        editAppInfoParam.setAppId(appInfoData.getAppId());
        editAppInfoParam.setAppName(appInfoData.getAppName());
        editAppInfoParam.setAppFrame(appInfoData.getAppFrame());
        editAppInfoParam.setAppGroup(appInfoData.getAppGroup());
        editAppInfoParam.setAppPackage(appInfoData.getAppPackage());
        editAppInfoParam.setAppLanguage(appInfoData.getAppLanguage());
        editAppInfoParam.setAppModule(appInfoData.getAppModule());
        editAppInfoParam.setAppType(appInfoData.getAppType());
        editAppInfoParam.setDepartmentId(appInfoData.getDepartmentId());
        editAppInfoParam.setDescribe(appInfoData.getDescribe());
        editAppInfoParam.setLanguageVersion(appInfoData.getLanguageVersion());
        editAppInfoParam.setTestPersons(testPersons.stream().map(TeamMember::getName).collect(Collectors.toList()));
        AlmpAppPersonList appPersonList = appPersonMap.get(appInfoData.getAppName());
        Assert.notNull(appPersonList);

        editAppInfoParam.setDevelopPersons(appPersonList.getDevelopPersons().stream().map(TeamMember::getName).collect(Collectors.toList()));
        editAppInfoParam.setObligationPerson(appPersonList.getObligationPerson().stream().map(TeamMember::getName).collect(Collectors.joining(",")));

        String url = "https://almp.shiguangkey.com/api/app-info/edit";
        HttpRequest postRequest = HttpUtil.createPost(url);
        Gson gson = new Gson();
        postRequest.body(gson.toJson(editAppInfoParam));
        postRequest.header("token", token);
        HttpResponse postResponse = postRequest.execute();
        Assert.isTrue(HttpStatus.HTTP_OK == postResponse.getStatus());

        ResponseCommon editResponse = gson.fromJson(postResponse.body(), ResponseCommon.class);
        Assert.isTrue(SUCCESS_CODE.equals(editResponse.getCode()));

        String reToken = postResponse.header("reToken");
        if (StringUtils.isNotEmpty(reToken) && !reToken.equals(token)) {
            token = reToken;
        }
    }
}